#include"socket.hpp"

#include"servercal.hpp"

#include<signal.h>

#define SIZE 1024

typedef std::string(*func)(std::string&);

class tcpserver
{
public:
    tcpserver(const int16_t& port, func slove) : _port(port), _slove(slove)
    {
    }

    void init()
    {
        _listen_sock.my_socket();
        _listen_sock.my_bind(_port);
        _listen_sock.my_listen();
    }

    void start()
    {
        signal(SIGPIPE, SIG_IGN);
        signal(SIGCHLD, SIG_IGN);

        while(1)
        {
            std::string ip;
            int16_t port;
            int sockfd = _listen_sock.my_accept(ip, port);
            // std::cout << sockfd << std::endl;

            if(fork() == 0)
            {
                _listen_sock.my_close();
                std::string message;
                while(1)
                {
                    char buffer[SIZE] = {0};
                    ssize_t ret = read(sockfd, buffer, SIZE);
                    message += buffer;
                    // std::cout << buffer << std::endl;
                    // std::cout << message << std::endl;
                    if(ret > 0)
                    {
                        // while(1)
                        // {
                            std::string back = _slove(message);
                            // std::cout << back << std::endl;
                            if(back.empty()) break;
                            write(sockfd, back.c_str(), back.size());
                        // }
                    }
                    else break;
                }
                exit(0);
            }
            close(sockfd);
        }
    }

    ~tcpserver()
    {
    }
private:
    sock _listen_sock;
    int16_t _port;
    func _slove;
};